class Province < ActiveRecord::Base
  has_paper_trail :version => :paper_trail_version, :versions => :paper_trail_versions
  belongs_to :country, :counter_cache => true
  has_many :cities, dependent: :destroy
  has_one :advertise_rule, :as => :advertise_ruleable, dependent: :destroy
  attr_accessible :code, :name, :country_id

  validates :name, presence: true
  validates_uniqueness_of :name, scope: :country_id
  validates :country_id, presence: true

  after_create :create_advertise_rule

  def this_advertise_group? advertise_group
    self.advertise_rule && self.advertise_rule.advertise_group_id && self.advertise_rule.advertise_group_id == advertise_group.id
  end

  def conflict_advertise_group? advertise_group
    self.advertise_rule && self.advertise_rule.advertise_group_id && self.advertise_rule.advertise_group_id != advertise_group.id
  end

  private

  def create_advertise_rule
    AdvertiseRule.create(advertise_ruleable_type: self.class.name, advertise_ruleable_id: self.id)
  end

end
